package handle

import (
	"fmt"
	"gitee.com/git_public/vfaith/builtin/bean"
	"gitee.com/git_public/vfaith/builtin/shape"
	"gitee.com/git_public/vfaith/builtin/vault"
	"gitee.com/git_public/vfaith/sugar"
	"gitee.com/git_public/vfaith/sugar/excelv"
	"log"
)

// FormHandler （查询条件）（List）
type FormHandler struct {
	*BlendHttp
	*shape.Map
	IsExport bool
}

func (handler *FormHandler) InitParam(dtoParamX ...bean.IxBaseEntityDTO) (*vault.QueryParam, error) {
	return handler.initParam(false, dtoParamX...)
}

func (handler *FormHandler) InitParamWithPage(dtoParamX ...bean.IxBaseEntityDTO) (*vault.QueryParam, error) {
	return handler.initParam(true, dtoParamX...)
}

func (handler *FormHandler) initParam(isPage bool, dtoParamX ...bean.IxBaseEntityDTO) (*vault.QueryParam, error) {
	dtoParam := sugar.GetDefaultArgs(dtoParamX, func() bean.IxBaseEntityDTO {
		return new(bean.NilDTO)
	})

	if err := MapUnmarshal(handler.Map, &dtoParam); err != nil {
		return nil, err
	}

	//校验获得的参数
	if err := dtoParam.InitDTO(); err != nil {
		return nil, fmt.Errorf("initParam，参数校验异常：%v", err)
	}

	queryParam := vault.NewQueryParam(isPage, handler.Map)
	queryParam.SetEntityParam(dtoParam)

	return queryParam, nil
}

func (handler *FormHandler) RenderPageOrExcel(data *vault.BundlePage, tmplPath string) {
	if handler.ReturnExcel(data.TableMap) {
		return
	}
	handler.RenderPage(data, tmplPath)
}

func (handler *FormHandler) ReturnExcel(data *vault.TableMap) bool {
	if !handler.IsExport {
		return false
	}

	w := handler.W
	f, _ := excelv.ExportExcel(data)

	// 设置HTTP头
	w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.xlsx", data.PageTitle))
	//w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.xlsx", f.GetSheetName(0)))

	_ = f.SetSheetName("Sheet1", "output")

	// 将Excel文件写入HTTP响应
	err := f.Write(w)
	if !handler.WriteErrorStr(err, fmt.Sprintf("回写Excel异常：【%s】", err)) {
		log.Println("Excel file successfully created and sent!")
	}

	return true
}
